package com.shop.loan.service.impl;

import com.alibaba.fastjson.JSON;
import com.shop.loan.model.UserAddress;
import com.shop.loan.model.common.Code;
import com.shop.loan.model.common.ResResult;
import com.shop.loan.model.vo.UserAddressVo;
import com.shop.loan.service.UserAddressService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import xyz.erupt.jpa.dao.EruptDao;

import javax.annotation.Resource;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Service
public class UserAddressServiceImpl implements UserAddressService {


    @Resource
    EruptDao eruptDao;

    @Transactional
    @Override
    public ResResult update(UserAddressVo userAddressVo) {
        if (userAddressVo.getId() == null) {
            return new ResResult(Code.PARAM_LACK);
        }
        if (userAddressVo.getIsDelete() != null && userAddressVo.getIsDelete()) {
//            userAddressVo.setDeleteTime(new Date());
            return new ResResult(Code.PARAM_INVALID);
        }
        UserAddress userAddress = JSON.parseObject(JSON.toJSONString(userAddressVo), UserAddress.class);
        eruptDao.getEntityManager().merge(userAddress);
        return new ResResult(Code.SUCCESS);
    }

    @Transactional
    @Override
    public ResResult add(UserAddressVo userAddressVo) {
        if (!StringUtils.hasLength(userAddressVo.getUserName()) || !StringUtils.hasLength(userAddressVo.getUserPhone()) || !StringUtils.hasLength(userAddressVo.getProvinceName()) || !StringUtils.hasLength(userAddressVo.getDetailInfo())) {
            return new ResResult(Code.PARAM_LACK);
        }

        UserAddress userAddress = JSON.parseObject(JSON.toJSONString(userAddressVo), UserAddress.class);
        userAddress.setRentalUserId(userAddressVo.getOpId());
        eruptDao.getEntityManager().persist(userAddress);
        if (userAddress.getId() != null) {
            return new ResResult(Code.SUCCESS);
        }
        return new ResResult(Code.FAIL);
    }

    @Override
    public ResResult list(UserAddressVo userAddressVo) {
        String sql = "select * from s_user_address where is_delete = false and rental_user_id = " + userAddressVo.getOpId();
        Query query = eruptDao.getEntityManager().createNativeQuery(sql, UserAddress.class);
        // 获取总结果集
        List<UserAddress> userAddressList = query.getResultList();
        return new ResResult(Code.SUCCESS, userAddressList);
    }
}
